package com.xh.chat.netty.event;

import com.xh.chat.netty.enums.MsgActionEnum;
import com.xh.chat.netty.annotation.EventProcess;
import com.xh.chat.netty.dto.ChatMsgDTO;
import com.xh.chat.netty.dto.DataContentDTO;
import com.xh.chat.netty.utils.ChannelUtil;
import com.xh.chat.service.UserService;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wen
 * @apiNote ConnectEventHandler
 * @since 2021-08-09
 */
@Service
@EventProcess(MsgActionEnum.CHAT)
public class ChatEventHandler implements EventHandler {

    @Autowired
    private UserService userService;

    @Override
    public void handle(DataContentDTO dataContentDTO, Channel currentChannel) {
        //  2.2  聊天类型的消息，把聊天记录保存到数据库，同时标记消息的签收状态[未签收]
        ChatMsgDTO chatMsgDTO = dataContentDTO.getChatMsgDTO();
        String msgText = chatMsgDTO.getMsg();
        Long receiverId = chatMsgDTO.getReceiverId();
        Long senderId = chatMsgDTO.getSenderId();

        // 保存消息到数据库，并且标记为 未签收
        Long msgId = userService.saveMsg(chatMsgDTO);
        chatMsgDTO.setMsgId(msgId);

        DataContentDTO dataContentDTOMsg = new DataContentDTO();
        dataContentDTOMsg.setChatMsgDTO(chatMsgDTO);

        // 发送消息
        ChannelUtil.sendByUserId(receiverId, dataContentDTOMsg);
    }

}
